package StackLeetCode;

import java.util.Stack;

public class TurnToSuffix {
    public static void main(String[] args) {
        String s = "(a+b)*c";
        System.out.println(turnSuffix(s));

        String s1 = "(a+b*c-d)*e";
        System.out.println(turnSuffix(s1));

        String s2 = "a*(b+c)";
        System.out.println(turnSuffix(s2));
    }

    public static String turnSuffix(String s) {
        if (s.length() == 0) {
            return null;
        }

        StringBuilder str = new StringBuilder();
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);

            switch (ch) {
                case '(' -> {
                    //如果是有括号，直接进栈
                    stack.push(ch);
                }
                case '+', '-','*','/' -> {
                    //比较优先级，进栈的优先级高，不需要弹出；进栈的优先级底或者同一级别，需要弹出。
                    while ( !stack.isEmpty() && priority(ch) <= priority(stack.peek())) {
                        str.append(stack.pop());
                    }
                    stack.push(ch);

                }
                case ')' -> {
                    while ( !stack.isEmpty() && stack.peek() != '(') {
                        str.append(stack.pop());
                    }
                    stack.pop();
                }
                default -> {
                    str.append(ch);
                }
            }

        }
        int num = stack.size();
        for (int j = 0; j < num; j++) {
            str.append(stack.pop());
        }
        return str.toString();
    }

    public static int priority(char f) {
        if (f == '(') {
            return 0;
        } else if (f == '+' || f == '-') {
            return 1;
        }else if (f == '*' || f == '/' ) {
            return 2;
        }
        return -1;
    }
}
